package com.risen.project.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.risen.project.excel.handler.ExcelHeadCheckHandler;

import java.util.Map;

/**
 * @author taoym
 * @date 2022/3/28 17:03
 * @description 抽象的表格读取监听器
 */
public abstract class AbstractReadListener<T> implements ReadListener<T> {

    /**
     * 错误信息
     */
    private String errorMsg;
    /**
     * 表头校验器
     */
    private ExcelHeadCheckHandler checkHandler;

    /**
     * excel映射的Java对象的Class对象
     */
    private Class<T> tClass;

    /**
     * @author taoym
     * @date 2022/3/30 15:28
     * @description 子类需要重写改方法 且再方法中调用父类中的该方法
     */
    @Override
    public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) {
        if (checkHandler != null) {
            boolean pass = checkHandler.check(headMap, tClass);
            if (!pass) {
                setErrorMsg("表格表头校验未通过");
                throw new ExcelAnalysisStopException("表格表头校验未通过");
            }
        }
    }

    /**
     * @author taoym
     * @date 2022/3/29 19:41
     * @description 这里需要throw异常 不然不会停止解析
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        throw exception;
    }


    @Override
    public void extra(CellExtra extra, AnalysisContext context) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public boolean hasNext(AnalysisContext analysisContext) {
        return true;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public void setCheckHandler(ExcelHeadCheckHandler checkHandler) {
        this.checkHandler = checkHandler;
    }

    public void settClass(Class<T> tClass) {
        this.tClass = tClass;
    }
}
